package com.yt.base.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;
import com.yt.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * 上传图片类
 * 
 * @author java
 * 
 */
public class UploadImageUtils {

    private static final Logger logger = LoggerFactory.getLogger(UploadImageUtils.class);


    private static SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
	/**
	 * 生成10位随机数
	 * 
	 * @return
	 */
	public static String getRandomNum() {
		return MD5Util.MD5(System.currentTimeMillis() + "").substring(0, 10);
	}
	
	private static OSSClient getClient() {
		return new OSSClient(ServiceConfig.OSS_END_POINT, ServiceConfig.OSS_ACCESS_ID, ServiceConfig.OSS_ACCESS_KEY);
	}
	
	public static boolean isFileExists(String folderName, String fileName) {
		boolean isExist = false;
		// 构造ListObjectsRequest请求
		ListObjectsRequest listObjectsRequest = new ListObjectsRequest(ServiceConfig.OSS_BUCKET_NAME);
		// "/" 为文件夹的分隔符
		listObjectsRequest.setDelimiter("/");
		// 列出fun目录下的所有文件和文件夹
		listObjectsRequest.setPrefix(folderName);
		ObjectListing listing = getClient().listObjects(listObjectsRequest);
		for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
			if (objectSummary.getKey().endsWith(fileName)) {
				isExist = true;
				break;
			}
		}
		return isExist;
	}
	
	/**
	 * 上传图片，返回图片的路径
	 * 
	 * @param folderName
	 * @param fileName
	 * @param is
	 * @param isOld
	 * @return
	 */
	public static String saveObject(String folderName, String fileName, InputStream is, boolean isOld) {
		// 如果是新添加的图片，则需要判断数据库是否存在相同的图片
		if (!isOld) {
			boolean isExit = false;
			do {
				isExit = isFileExists(folderName, fileName);
				if (isExit) {
					// 保存路径
					Calendar cal = Calendar.getInstance();
					StringBuffer sb = new StringBuffer();
					sb.append("activity").append("/");
					sb.append(cal.get(Calendar.YEAR)).append("/");
					sb.append((cal.get(Calendar.MONTH) + 1) > 9 ? (cal.get(Calendar.MONTH) + 1) : "0" + (cal.get(Calendar.MONTH) + 1)).append("/");
					sb.append(cal.get(Calendar.DATE) > 9 ? cal.get(Calendar.DATE) : "0" + cal.get(Calendar.DATE)).append("/");
					folderName = sb.toString();
					// 文件名
					String fileExt = fileName.substring(fileName.length() - 4);
					fileName = UploadImageUtils.getRandomNum() + fileExt;
				}
			} while (isExit);
		}
		// !!相同名称会覆盖
		String resulut = null;
		try {
			//文件大小
//			System.out.println("文件大小："+is.available());
//			if(is.available()>=5*1024*1024){
//				OSSUploadBigFileUtil.uploadBigFile(folderName + fileName,is);
//			}else {
				ObjectMetadata objectMeta = new ObjectMetadata();
				objectMeta.setContentLength(is.available());
				PutObjectResult result = getClient().putObject(ServiceConfig.OSS_BUCKET_NAME, folderName + fileName, is, objectMeta);
//			}
			// 打印ETag
			//System.out.println(result.getETag());
			resulut = folderName + fileName;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				is.close();
			} catch (IOException e) {
			}
		}
		return resulut;
	}
	
	/**
	 * 上传文件
	 * 
	 * @param pic
	 * @param folder
	 * @return
	 */
	public static  String uploadImage(MultipartFile pic, String folder) {
		try {
			if (pic != null && pic.getSize() > 0) {
				String fileName = null;
				String path = null;
				boolean isOld = false;
				// 保存路径
				Calendar cal = Calendar.getInstance();
				StringBuffer sb = new StringBuffer();
				sb.append(folder == null ? "test" : folder).append("/");
				sb.append(cal.get(Calendar.YEAR)).append("/");
				sb.append((cal.get(Calendar.MONTH) + 1) > 9 ? (cal.get(Calendar.MONTH) + 1) : "0" + (cal.get(Calendar.MONTH) + 1)).append("/");
				sb.append(cal.get(Calendar.DATE) > 9 ? cal.get(Calendar.DATE) : "0" + cal.get(Calendar.DATE)).append("/");
				path = sb.toString();
				// 文件名
				String fileExt = pic.getOriginalFilename().substring(pic.getOriginalFilename().lastIndexOf("."));
				fileName = UploadImageUtils.getRandomNum() + fileExt.toLowerCase();
				String result = saveObject(path, fileName, pic.getInputStream(), isOld);
				if (StringUtils.isNotEmpty(result)) {
					return result;
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}


	/**
	 * 上传文件
	 * 
	 * @param pic
	 * @param folder
	 * @return
	 */
	public static  String uploadImage(File pic, String folder,String fileExt) {
		try {
			if (pic != null) {
				String fileName = null;
				String path = null;
				boolean isOld = false;
				// 保存路径
				Calendar cal = Calendar.getInstance();
				StringBuffer sb = new StringBuffer();
				sb.append(folder == null ? "test" : folder).append("/");
				sb.append(cal.get(Calendar.YEAR)).append("/");
				sb.append((cal.get(Calendar.MONTH) + 1) > 9 ? (cal.get(Calendar.MONTH) + 1) : "0" + (cal.get(Calendar.MONTH) + 1)).append("/");
				sb.append(cal.get(Calendar.DATE) > 9 ? cal.get(Calendar.DATE) : "0" + cal.get(Calendar.DATE)).append("/");
				path = sb.toString();
				// 文件名
				fileName = UploadImageUtils.getRandomNum() + "." + fileExt.toLowerCase();
				InputStream is = new FileInputStream(pic);
				String result = saveObject(path, fileName, is, isOld);
				if (StringUtils.isNotEmpty(result)) {
					return result;
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 检测图片是否是正方形
	 * @param file
	 * @param request
	 * @return
	 */
	public static  boolean checkImageIsSquare(MultipartFile file, HttpServletRequest request) {
		File dir = new File(request.getSession().getServletContext().getRealPath("") );
		if (!dir.exists()) {
			dir.mkdir();
		}
		String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		File picture = new File(request.getSession().getServletContext().getRealPath("")  + File.separator + System.currentTimeMillis() + fileExt);
		 byte[] advImageBytes = null;  
		try {
			picture.createNewFile();
			 InputStream advImageStream = file.getInputStream();
			 advImageBytes = FileCopyUtils.copyToByteArray(advImageStream);
			 FileCopyUtils.copy(advImageBytes, picture);
			 advImageStream.close();  
			BufferedImage image = ImageIO.read(picture);
//			System.out.println("宽度："+image.getWidth()+"===============高度："+image.getHeight());
			if (image.getWidth() == image.getHeight()) {
				return true;
			}
			picture.delete();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 检测图片大小是否符合规定
	 * @param file
	 * @param request
	 * @return
	 */
	public static  boolean checkImage(MultipartFile file, double width, double height, HttpServletRequest request) {
		try {
			BufferedImage image = ImageIO.read(file.getInputStream());
			if (image.getWidth() == width && image.getHeight() == height) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

    /**
     * 获取图片的宽度和高度
     * @param file
     * @param request
     * @return
     */
    public static  int []  getImageWH(MultipartFile file, HttpServletRequest request) {
		try {
            BufferedImage image = ImageIO.read(file.getInputStream());
            int [] wh=new int[2];
            wh[0]=image.getWidth();
            wh[1]=image.getHeight();
            return wh;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String getFileNameAndCheckSuffix(MultipartFile file){
        String fileName=file.getOriginalFilename();
        String suffix=fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
        fileName=MD5Util.MD5(fileName+System.currentTimeMillis())+"."+suffix;

        return fileName;
    }

    private static void saveAliYun(MultipartFile file, String path){
        InputStream is=null;
        try {
            is=file.getInputStream();
            ObjectMetadata objectMeta = new ObjectMetadata();
            objectMeta.setContentLength(is.available());
            PutObjectResult result=	getClient().putObject(ServiceConfig.OSS_BUCKET_NAME,  path, is, objectMeta);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("上传图片失败");
        } finally {
            try {
                if(is!=null){
                    is.close();
                }
            } catch (IOException e) {
            }
        }
    }


	/**
	 * 上传文件
	 *
	 * @param file
	 * @param folder
	 * @return
	 */
	public static  String uploadFile(File file, String folder) {
		try {
			if (file != null) {
				String path = null;
				boolean isOld = true;
				// 保存路径
				Calendar cal = Calendar.getInstance();
				StringBuffer sb = new StringBuffer();
				sb.append(folder == null ? "test" : folder).append("/");
				sb.append(cal.get(Calendar.YEAR)).append("/");
				sb.append((cal.get(Calendar.MONTH) + 1) > 9 ? (cal.get(Calendar.MONTH) + 1) : "0" + (cal.get(Calendar.MONTH) + 1)).append("/");
				sb.append(cal.get(Calendar.DATE) > 9 ? cal.get(Calendar.DATE) : "0" + cal.get(Calendar.DATE)).append("/");
				path = sb.toString();
				// 文件名
//				fileName = UploadImageUtils.getRandomNum() + "." + fileExt.toLowerCase();
				InputStream is = new FileInputStream(file);
				String result = saveObject(path, file.getName(), is, isOld);
				if (StringUtils.isNotEmpty(result)) {
					return result;
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
}
